package slave

import (
	"fmt"

	mb "github.com/tbrandon/mbserver"
)

type TcpSlave struct {
	port   int    `default:"502"`
	ip     string `default:"0.0.0.0"`
	server *mb.Server
}

func CreateNew(ip string, port int) (*TcpSlave, error) {
	s := new(TcpSlave)
	s.SetPort(port)
	s.SetIp(ip)
	err := s.Start()
	return s, err
}

func (s *TcpSlave) Start() error {
	if s.server == nil {
		s.server = mb.NewServer() // argument for constructor determines the ModbusSlave-ID
	}
	err := s.server.ListenTCP(fmt.Sprintf("%v:%d", s.ip, s.port))
	return err
}
func (s *TcpSlave) Stop() {
	if s.server != nil {
		s.server.Close()
	}
}

func (s *TcpSlave) SetPort(port int) {
	if port > 0 {
		s.port = port
	}
}

func (s *TcpSlave) SetIp(ip string) {
	s.ip = ip
}
